package com.example.nowcodercommunity.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.nowcodercommunity.annotation.LoginRequire;
import com.example.nowcodercommunity.entity.Event;
import com.example.nowcodercommunity.entity.Message;
import com.example.nowcodercommunity.entity.Page;
import com.example.nowcodercommunity.entity.User;
import com.example.nowcodercommunity.service.CommunityConstant;
import com.example.nowcodercommunity.service.MessageService;
import com.example.nowcodercommunity.service.UserService;
import com.example.nowcodercommunity.util.CommunityUtil;
import com.example.nowcodercommunity.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;

import java.util.*;

@Controller
public class MessageController implements CommunityConstant {

    @Autowired
    private MessageService messageService;

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;

    /**
     * 私信列表
     * @param model
     * @param page
     * @return
     */
    @LoginRequire
    @RequestMapping(path = "/letter/list",method = RequestMethod.GET)
    public String getLetterList(Model model, Page page){
        // 查询当前用户
        User user = hostHolder.getUser();

        // 设置分页信息
        page.setLimit(5);
        page.setSearchPath("/letter/list");
        page.setTotalRows(messageService.getCountOnConversation(user.getId()));

        // 查询私信情况并注入Model对象交给前端
        List<Message> conversationList = messageService.getConversationsByUserId(user.getId(), page.getFrom(), page.getLimit());

        List<Map<String,Object>> conversations = new ArrayList<>();
        if(conversationList!=null){
            for(Message message:conversationList){
                Map<String,Object> map = new HashMap<>();
                map.put("conversation",message);
                map.put("unreadCount",messageService.getCountOnUnreadLetter(user.getId(),message.getConversationId()));
                map.put("letterCount",messageService.getCountOnLetter(message.getConversationId()));
                int targetId = (user.getId()==message.getFromId())? message.getToId() : message.getFromId();
                User targetUser = userService.findUserById(targetId);
                map.put("target",targetUser);

                conversations.add(map);
            }
        }
        model.addAttribute("conversations",conversations);

        // 查询未读消息数量
        int unreadNoticeCount = messageService.getUnreadNoticeCount(user.getId(), null);
        model.addAttribute("noticeUnreadCount", unreadNoticeCount);
        int unreadLetterCount = messageService.getCountOnUnreadLetter(user.getId(), null);
        model.addAttribute("letterUnreadCount",unreadLetterCount);

        return "/site/letter";
    }

    /**
     * 查看私信详情
     * @param conversationId
     * @param page
     * @param model
     * @return
     */
    @LoginRequire
    @RequestMapping(path = "/letter/detail/{conversationId}",method = RequestMethod.GET)
    public String getLetterDetail(@PathVariable(name = "conversationId") String conversationId,Page page,Model model){
        page.setLimit(5);
        page.setSearchPath("/letter/detail/"+conversationId);
        page.setTotalRows(messageService.getCountOnLetter(conversationId));

        List<Message> messages = messageService.getMessagesByConversation(conversationId, page.getFrom(), page.getLimit());
        List<Map<String,Object>> letters = new LinkedList<>();

        if(messages!=null){
            for(Message message:messages){
                Map<String,Object> map = new HashMap<>();
                map.put("letter",message);
                map.put("fromUser",userService.findUserById(message.getFromId()));
                letters.add(map);
            }
        }
        model.addAttribute("letters",letters);

        User partner = findConvPartner(conversationId);
        model.addAttribute("target",partner);

        List<Integer> unreadMessagesIds = getUnreadMessagesIds(messages);
        if(unreadMessagesIds.size()>0){
            messageService.readMessage(unreadMessagesIds);
        }

        return "/site/letter-detail";
    }

    /**
     * 用于查找私信对方的账户
     * @param conversationId
     * @return
     */
    private User findConvPartner(String conversationId){
        String[] ids = conversationId.split("_");
        if(ids.length!=2){
            throw new RuntimeException("无法通过会话号找到对方ID！");
        }
        int id1 = Integer.parseInt(ids[0]);
        int id2 = Integer.parseInt(ids[1]);

        int partnerId = (id1==hostHolder.getUser().getId())?id2:id1;

        return userService.findUserById(partnerId);
    }

    /**
     * 用于从我们获取的通信列表中筛选出目标人为当前用户且未读的消息
     * @param messageList
     * @return
     */
    private List<Integer> getUnreadMessagesIds(List<Message> messageList){
        List<Integer> ids = new ArrayList<>();

        if(messageList!=null){
            for(Message message:messageList){
                if(message.getToId()==hostHolder.getUser().getId()&&message.getStatus()==0){
                    ids.add(message.getId());
                }
            }
        }

        return ids;
    }

    /**
     * 发送私信
     * @param toName
     * @param content
     * @return
     */
    @RequestMapping(path = "/letter/send",method = RequestMethod.POST)
    @ResponseBody
    @LoginRequire
    public String sendMessage(String toName,String content){
        User toUser = userService.findUserByName(toName);
        if(toUser==null){
            return CommunityUtil.getJSONString(1,"目标用户不存在");
        }

        Message message = new Message();

        message.setContent(content);
        message.setToId(toUser.getId());
        message.setFromId(hostHolder.getUser().getId());
        message.setCreateTime(new Date());
        String conversationId = "";

        if(hostHolder.getUser().getId()<toUser.getId()){
            conversationId = hostHolder.getUser().getId()+"_"+toUser.getId();
        }else{
            conversationId = toUser.getId()+"_"+hostHolder.getUser().getId();
        }
        message.setConversationId(conversationId);

        messageService.addMessage(message);

        return CommunityUtil.getJSONString(0);
    }

    /**
     * 查看通知列表
     * @param model
     * @return
     */
    @RequestMapping(path = "/notice/list", method = RequestMethod.GET)
    public String getNoticeList(Model model){
        User user = hostHolder.getUser();

        // 查询三类系统通知，整合进入model
        Message message = messageService.getNewestNotice(user.getId(), TOPIC_COMMENT);
        Map<String, Object> messageVO = new HashMap<>();
        if(message != null){
            messageVO.put("message", message);

            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVO.put("user", userService.findUserById((Integer) data.get("userId")));
            messageVO.put("entityType", data.get("entityType"));
            messageVO.put("entityId", data.get("entityId"));
            messageVO.put("postId", data.get("postId"));

            int count = messageService.getNoticeCount(user.getId(), TOPIC_COMMENT);
            messageVO.put("count", count);

            int unreadCount = messageService.getUnreadNoticeCount(user.getId(), TOPIC_COMMENT);
            messageVO.put("unread", unreadCount);
            model.addAttribute("commentNotice" ,messageVO);
        }

        // 点赞
        message = messageService.getNewestNotice(user.getId(), TOPIC_LIKE);
        messageVO = new HashMap<>();
        if(message != null){
            messageVO.put("message", message);

            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVO.put("user", userService.findUserById((Integer) data.get("userId")));
            messageVO.put("entityType", data.get("entityType"));
            messageVO.put("entityId", data.get("entityId"));
            messageVO.put("postId", data.get("postId"));

            int count = messageService.getNoticeCount(user.getId(), TOPIC_LIKE);
            messageVO.put("count", count);

            int unreadCount = messageService.getUnreadNoticeCount(user.getId(), TOPIC_LIKE);
            messageVO.put("unread", unreadCount);
            model.addAttribute("likeNotice" ,messageVO);
        }

        // 关注
        message = messageService.getNewestNotice(user.getId(), TOPIC_FOLLOW);
        messageVO = new HashMap<>();
        if(message != null){
            messageVO.put("message", message);
            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVO.put("user", userService.findUserById((Integer) data.get("userId")));
            messageVO.put("entityType", data.get("entityType"));
            messageVO.put("entityId", data.get("entityId"));

            int count = messageService.getNoticeCount(user.getId(), TOPIC_FOLLOW);
            messageVO.put("count", count);

            int unreadCount = messageService.getUnreadNoticeCount(user.getId(), TOPIC_FOLLOW);
            messageVO.put("unread", unreadCount);
            model.addAttribute("followNotice" ,messageVO);
        }

        //
        int unreadNoticeCount = messageService.getUnreadNoticeCount(user.getId(), null);
        model.addAttribute("noticeUnreadCount", unreadNoticeCount);
        int unreadMessageCount = messageService.getCountOnUnreadLetter(user.getId(), null);
        model.addAttribute("letterUnreadCount", unreadMessageCount);

        return "/site/notice";
    }

    /**
     * 通知详情
     * @param topic
     * @param page
     * @param model
     * @return
     */
    @RequestMapping(path = "/notice/detail/{topic}", method = RequestMethod.GET)
    public String getNoticesDetail(@PathVariable(name = "topic")String topic, Page page, Model model){
        User user = hostHolder.getUser();

        page.setLimit(5);
        page.setSearchPath("/notice/detail/"+topic);
        page.setTotalRows(messageService.getNoticeCount(user.getId(), topic));

        List<Message> notices = messageService.getNotices(user.getId(), topic, page.getFrom(), page.getLimit());
        List<Map<String, Object>> noticeVoList = new ArrayList<>();

        if(notices != null){
            for(Message notice : notices){
                Map<String, Object> map = new HashMap<>();
                map.put("notice", notice);

                String content = HtmlUtils.htmlUnescape(notice.getContent());
                Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

                map.put("user", userService.findUserById((Integer) data.get("userId")));
                map.put("entityType", data.get("entityType"));
                map.put("entityId", data.get("entityId"));
                map.put("postId", data.get("postId"));

                map.put("fromUser", userService.findUserById(notice.getFromId()));

                noticeVoList.add(map);
            }
        }
        model.addAttribute("notices", noticeVoList);

        List<Integer> ids = getUnreadMessagesIds(notices);
        if(!ids.isEmpty()){
            messageService.readMessage(ids);
        }

        return "/site/notice-detail";
    }
}
